﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Net;
using System.IO;

namespace TaobalLibrary.Requests
{
    public class Requests
    {
        public static string GetText(string url, Dictionary<string, string> headers = null, CookieContainer cookies = null, string encoding = "GBK")
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            if (headers != null)
            {
                foreach (KeyValuePair<string, string> entry in headers)
                {
                    request.Headers[entry.Key] = entry.Value;
                }
            }
            request.CookieContainer = cookies;
            HttpWebResponse response = null;
            Stream responseStream = null;
            StreamReader responseReader = null;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
                responseStream = response.GetResponseStream();
                responseReader = new StreamReader(responseStream, Encoding.GetEncoding(encoding));
                return responseReader.ReadToEnd();
            }
            finally
            {
                if (responseReader != null)
                    responseReader.Close();
                if (responseStream != null)
                    responseStream.Close();
                if (response != null)
                    response.Close();
            }
        }

        public static byte[] GetByte(string url, Dictionary<string, string> headers = null, CookieContainer cookies = null)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            if (headers != null)
            {
                foreach (KeyValuePair<string, string> entry in headers)
                {
                    request.Headers[entry.Key] = entry.Value;
                }
            }
            request.CookieContainer = cookies;
            HttpWebResponse response = null;
            Stream responseStream = null;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
                responseStream = response.GetResponseStream();
                byte[] readBuff = new byte[response.ContentLength];
                responseStream.Read(readBuff, 0, readBuff.Length);
                return readBuff;
            }
            finally
            {
                if (responseStream != null)
                    responseStream.Close();
                if (response != null)
                    response.Close();
            }
        }
    }
}
